import os
import shutil
from datetime import datetime

from constant import FAILURE, SUCCESS, CRAWL_TYPE_REPO
from logger import logger
from store import tasks

"""
定时清理任务
"""
def clean_task_job():
    current_time = datetime.now()
    for task_id, task in list(tasks.items()):
        logger.info(f"正在清理任务{task_id}")
        if task['status'] == FAILURE or (task['status'] == SUCCESS and current_time > task['expiryTime']):
            if task['crawlType'] == CRAWL_TYPE_REPO:
                # 删除任务相关的文件
                save_dir = f"download/{task_id}"
                logger.info(f"正在删除任务{task_id}的残留文件")
                if os.path.exists(save_dir):
                    shutil.rmtree(save_dir)
                    logger.info(f"成功删除任务{task_id}中文件夹{save_dir}")
                zip_file = save_dir + '.zip'
                if os.path.exists(zip_file):
                    os.remove(zip_file)
                logger.info(f"成功删除任务{task_id}中压缩包{zip_file}")
            else:
                save_file_path = f"download/{task_id}/{task['docTitle']}.md"
                if os.path.exists(save_file_path):
                    os.remove(save_file_path)
                    logger.info(f"成功删除任务{task_id}中文件{save_file_path}")
            # 删除任务
            del tasks[task_id]